package com.shop.bookstore.service;

import com.shop.bookstore.dao.BookDao;
import com.shop.bookstore.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class BookService implements BookDao {
//    实现操作方法增删改查
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public int add(Book book) {
        String sql = "insert into book values(null,?,?,?,?,?,?)";
//        调用方法实现
        Object[] args = {book.getBookname(),book.getAuthor(),book.getNumber(),book.getPricing(),book.getPublishers(),book.getType()};
        return jdbcTemplate.update(sql, args);

    }

    @Override
    public int delete(Book book) {
        String sql = "delete from book where Id=?";
        Object[] args={book.getId()};
        return jdbcTemplate.update(sql, args);
    }

    /**
     * 更新商品操作
     * @param book
     * @return
     */

    @Override
    public int update(Book book) {
        String sql = "update book set bookname=?,author=?,number=?,pricing=?,publishers=?,type=? where Id=?";
        Object[] args={
                book.getBookname(),book.getAuthor(),book.getNumber(),book.getPricing(),book.getPublishers(),book.getType(),
                book.getId()
        };
        return jdbcTemplate.update(sql, args);
    }

    /***
     *
     * @param book
     * @return
     */
    @Override
    public Book findOne(Book book) {
        String sql = "select * from book where Id="+book.getId().toString();
        return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Book>(Book.class));
    }

    /**
     * 获取所有商品列表的方法
     * @return
     */
    @Override
    public List<Book> findAll() {
        String sql = "select * from book";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
    }

}
